#include "chatClient.h"

void ChatClient::errLog(const char *msg)
{
    cerr << __FILE__ << ":" << __func__ << " " << __LINE__ << endl;
    perror(msg);
}

void ChatClient::sendMsg(int type, const string &text)
{
    MSG msg;
    msg.type = htonl(type); // 网络字节序转换
    strncpy(msg.name, name.c_str(), sizeof(msg.name));
    strncpy(msg.text, text.c_str(), sizeof(msg.text));

    string data = msg.serialize();

    if (send(cfd, data.c_str(), data.size(), 0) < 0)
    {
        errLog("send error");
        return;
    }
    cout << "消息发送成功\n";

    // if(text == "quit")
    // {
    //     running = false;
    //     exit(EXIT_SUCCESS);
    // }
}

void ChatClient::recvMsg()
{
    char buffer[sizeof(MSG)];
    while (running)
    {
        int recv_len = recv(cfd, buffer, sizeof(buffer), MSG_DONTWAIT); // 非阻塞接收
        if (recv_len <= 0)
        {
            if (errno == EAGAIN) // 无数据可读，继续等待
            {
                usleep(1000);
                continue;
            }
            else
            {
                errLog("recv error");
                running = false;
                return;
            }
        }
        else
        {
            MSG msg;
            msg.deserialize(string(buffer, recv_len));
            cout << msg.name << ": " << msg.text << endl;
        }
    }
}

ChatClient::ChatClient(const char *ip, int port, const string &name)
    : name(name), running(true)
{
    // 创建客户端套接字
    cfd = socket(AF_INET, SOCK_STREAM, 0);
    if (cfd < 0)
    {
        errLog("create socket error");
        return;
    }

    // 连接服务器
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = inet_addr(ip);
    if (connect(cfd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    {
        errLog("connect error");
        return;
    }

    sendMsg(LOGIN);
}

ChatClient::~ChatClient()
{
    sendMsg(QUIT);
    close(cfd);
}

void ChatClient::run()
{
    // 创建一个分支线程，主要用于接收服务端的消息
    thread recvThread(&ChatClient::recvMsg, this);

    // 主线程向服务器发送消息
    string text;
    while (running)
    {
        getline(cin, text);

        if (text == "quit")
        {
            running = false;
            break;
        }

        sendMsg(CHAT, text);
    }

    recvThread.join(); // 等待接收线程结束
}